import { importPayableStatementApi, downloadTemplateApi } from "@/api/financialManagement/payableManagement";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import { Ref } from "vue";
import CommonHook from "@/hook/commonHook";
export default function OperationHook(state: { formState: { companyId: string | undefined; file: Array<File> }; formDataRef: Ref<any>; emit: any; loading: Ref<boolean>; type: Ref<number> }) {
  const { formState, formDataRef, emit, loading, type } = state;
  const { resetFields, validateZhInputHandle } = FormHook({ formState });
  const { downloadFileByUrl, exportJsonToExcel } = CommonHook();
  const onFinish = () => {
    const { file, companyId } = formState;
    const params: any = {
      companyId,
      statementType: type.value
    };
    const formData = new FormData();
    formData.append("file", file[0]);
    loading.value = true;
    importPayableStatementApi(params, formData)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          if (!data) {
            message.success("操作成功!");
            emit("submit");
          } else {
            message.error("导入失败， 对应失败原因已下载!");
            const header = [["运单号", "错误原因"]];
            exportJsonToExcel(header, data || [], "导入错误原因");
          }
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const uploadRequest = (e: any) => {
    formState.file = [e.file];
    e.onProgress({ percent: 100 });
  };
  // 下载模板
  const downloadTemplateHandle = () => {
    return downloadTemplateApi({ type: 5 }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        downloadFileByUrl(data, type.value === 1 ? "导入对账单.xlsx" : "导入加收单.xlsx");
      }
    });
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    validateZhInputHandle,
    uploadRequest,
    downloadTemplateHandle
  };
}
